package com.yunxin.admin.system.api.download;

import com.yunxin.admin.system.api.download.extenal.DownloadFileCommand;
import com.yunxin.admin.system.application.UserQueryService;
import com.yunxin.admin.system.application.dto.UserDetailDTO;
import com.yunxin.admin.system.infra.common.constant.SecurityConstants;
import com.yunxin.admin.system.infra.framework.resubmit.Resubmit;
import com.yunxin.admin.system.infra.framework.security.util.SecurityUtils;
import com.yunxin.admin.system.infra.framework.syslog.AutoLog;
import com.yunxin.common.exception.BusinessException;
import com.yunxin.common.result.Result;
import com.yunxin.core.admin.domain.AdminUser;
import com.yunxin.core.customer.dto.CustomerPageDto;
import com.yunxin.core.customer.dto.CustomerRunPageDto;
import com.yunxin.core.customer.dto.CustomerWechatPageDto;
import com.yunxin.core.utils.infra.utils.BeanCopierUtils;
import com.yunxin.core.utils.infra.utils.DateFormatUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.web.bind.annotation.*;
import java.util.*;

/**
 * @author zero°
 * @since 2023-06-15
 */
@Tag(name = "2.导出")
@RestController
@RequiredArgsConstructor
@RequestMapping("/download/file")
public class DownloadFileController {


    private static final String BOKE_SOURCE = "crm";


    private static final String START_ALLOCATION_TIME = "startAllocationTime";

    private static final String END_ALLOCATION_TIME = "endAllocationTime";

    private static final String START_SUBMIT_TIME = "startSubmitTime";

    private static final String END_SUBMIT_TIME = "endSubmitTime";


    private final DownloadFileHandle downloadFileHandle;

    private final UserQueryService userQueryService;



    @Operation(summary = "导出企微客户", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @GetMapping("/downloadWeChatUser")
//    @PreAuthorize("@ss.hasPerm('download:merchant:user')")
    @Resubmit
    @AutoLog(value = "导出企微客户")
    public Result<Boolean> downloadWeChatUser(@ParameterObject CustomerWechatPageDto command) {
        Map<String, Object> map = BeanCopierUtils.X.convertClassToMap(command);
        Long userId = SecurityUtils.X.getUser().getUserId();
        // 判断用户导出权限
        AdminUser adminUser = getUserInfoByUserId(userId);
        if(adminUser.getExport()==2){
            throw new BusinessException("没有导出权限");
        }
        List<Long> merchantIds = userQueryService.getUserMerchantIds(userId);
        map.put("merchantIds", merchantIds);
        downloadFile(BOKE_SOURCE,"weChatUser", map,adminUser.getIsView());
        return Result.success();
    }

    @Operation(summary = "导出分配单列表", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @GetMapping("/downloadCustomerUser")
//    @PreAuthorize("@ss.hasPerm('download:merchant:user')")
    @Resubmit
    @AutoLog(value = "导出分配单列表")
    public Result<Boolean> downloadCustomerUser(@ParameterObject CustomerPageDto command) {
        Map<String, Object> map = BeanCopierUtils.X.convertClassToMap(command);
        Long userId = SecurityUtils.X.getUser().getUserId();
        // 判断用户导出权限
        AdminUser adminUser = getUserInfoByUserId(userId);
        if(adminUser.getExport()==2){
            throw new BusinessException("没有导出权限");
        }
        List<Long> merchantIds = userQueryService.getUserMerchantIds(userId);
        map.put("merchantIds", merchantIds);
        downloadFile(BOKE_SOURCE,"customerUser", map,adminUser.getIsView());
        return Result.success();
    }


    @Operation(summary = "导出流失客户列表", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @GetMapping("/downloadRunCustomerUser")
//    @PreAuthorize("@ss.hasPerm('download:merchant:user')")
    @Resubmit
    @AutoLog(value = "导出流失客户列表")
    public Result<Boolean> downloadRunCustomerUser(@ParameterObject CustomerRunPageDto command) {
        Map<String, Object> map = BeanCopierUtils.X.convertClassToMap(command);
        Long userId = SecurityUtils.X.getUser().getUserId();
        // 判断用户导出权限
        AdminUser adminUser = getUserInfoByUserId(userId);
        if(adminUser.getExport()==2){
            throw new BusinessException("没有导出权限");
        }
        List<Long> merchantIds = userQueryService.getUserMerchantIds(userId);
        map.put("merchantIds", merchantIds);
        downloadFile(BOKE_SOURCE,"runCustomerUser", map,adminUser.getIsView());
        return Result.success();
    }


    @Operation(summary = "导出业务员客户列表", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @GetMapping("/downloadSalesmanCustomerUser")
//    @PreAuthorize("@ss.hasPerm('download:merchant:user')")
    @Resubmit
    @AutoLog(value = "导出业务员客户列表")
    public Result<Boolean> downloadSalesmanCustomerUser(@ParameterObject CustomerRunPageDto command) {
        Map<String, Object> map = BeanCopierUtils.X.convertClassToMap(command);
        Long userId = SecurityUtils.X.getUser().getUserId();
        // 判断用户导出权限
        AdminUser adminUser = getUserInfoByUserId(userId);
        if(adminUser.getExport()==2){
            throw new BusinessException("没有导出权限");
        }
        List<Long> merchantIds = userQueryService.getUserMerchantIds(userId);
        map.put("merchantIds", merchantIds);
        downloadFile(BOKE_SOURCE,"salesmanCustomerUser", map,adminUser.getIsView());
        return Result.success();
    }


    @Operation(summary = "导出话务员客户列表", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @GetMapping("/downloadTelephonerCustomerUser")
//    @PreAuthorize("@ss.hasPerm('download:merchant:user')")
    @Resubmit
    @AutoLog(value = "导出话务员客户列表")
    public Result<Boolean> downloadTelephonerCustomerUser(@ParameterObject CustomerRunPageDto command) {
        Map<String, Object> map = BeanCopierUtils.X.convertClassToMap(command);
        Long userId = SecurityUtils.X.getUser().getUserId();
        // 判断用户导出权限
        AdminUser adminUser = getUserInfoByUserId(userId);
        if(adminUser.getExport()==2){
            throw new BusinessException("没有导出权限");
        }
        List<Long> merchantIds = userQueryService.getUserMerchantIds(userId);
        map.put("merchantIds", merchantIds);
        downloadFile(BOKE_SOURCE,"telephonerCustomerUser", map,adminUser.getIsView());
        return Result.success();
    }


    /**
     * 下载文件
     * @param dataSourceName dataSourceName
     * @param methodCode methodCode
     * @param param param
     */
    private void downloadFile(String dataSourceName, String methodCode, Map<String, Object> param, Integer isView){
        DownloadFileCommand downloadFileCommand = new DownloadFileCommand();
        downloadFileCommand.setDataSourceName(dataSourceName);
        downloadFileCommand.setMethodCode(methodCode);
        downloadFileCommand.setDownloaderName(SecurityUtils.X.getUser().getUsername());
        downloadFileCommand.setParams(param);
        downloadFileCommand.setIsView(isView);
        downloadFileHandle.downloadFileAsync(downloadFileCommand);
    }

    /**
     * 下载商户发票文件
     * @param dataSourceName dataSourceName
     * @param methodCode methodCode
     * @param param param
     */
    private void downloadWorldFile(String dataSourceName, String methodCode, Map<String, Object> param, Integer isView){
        DownloadFileCommand downloadFileCommand = new DownloadFileCommand();
        downloadFileCommand.setDataSourceName(dataSourceName);
        downloadFileCommand.setMethodCode(methodCode);
        downloadFileCommand.setDownloaderName(SecurityUtils.X.getUser().getUsername());
        downloadFileCommand.setParams(param);
        downloadFileCommand.setIsView(isView);
        downloadFileHandle.downloadWorldFileAsync(downloadFileCommand);
    }

    /**
     * 处理导出订单时间
     * @param map map
     */
    private void dealDownloadOrderTime(Map<String, Object> map){
        if (Objects.nonNull(map.get(START_ALLOCATION_TIME))) {
            map.put(START_ALLOCATION_TIME, map.get(START_ALLOCATION_TIME) + DateFormatUtils.TIME_START);
        }
        if (Objects.nonNull(map.get(END_ALLOCATION_TIME))) {
            map.put(END_ALLOCATION_TIME, map.get(END_ALLOCATION_TIME) + DateFormatUtils.TIME_END);
        }
        if (Objects.nonNull(map.get(START_SUBMIT_TIME))) {
            map.put(START_SUBMIT_TIME, map.get(START_SUBMIT_TIME) + DateFormatUtils.TIME_START);
        }
        if (Objects.nonNull(map.get(END_SUBMIT_TIME))) {
            map.put(END_SUBMIT_TIME, map.get(END_SUBMIT_TIME) + DateFormatUtils.TIME_END);
        }
    }

    private AdminUser getUserInfoByUserId(Long userId){
        return userQueryService.getUserInfoById(userId);

    }
}
